{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "initial_id",
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    ""
   ]
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 关于LCEL语法的使用\n",
    "\n",
    "在使用 | 之前的举例:"
   ],
   "id": "b8c14f7cb3a4bc85"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-29T01:15:43.985750Z",
     "start_time": "2025-09-29T01:15:40.825330Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "# 引入依赖包\n",
    "from langchain_core.output_parsers import JsonOutputParser\n",
    "from langchain_core.prompts import PromptTemplate\n",
    "import os\n",
    "import dotenv\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "dotenv.load_dotenv()\n",
    "\n",
    "os.environ['OPENAI_API_KEY'] = os.getenv(\"OPENAI_API_KEY1\")\n",
    "os.environ['OPENAI_BASE_URL'] = os.getenv(\"OPENAI_BASE_URL\")\n",
    "\n",
    "# 初始化语言模型\n",
    "chat_model = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "joke_query = \"告诉我一个笑话。\"\n",
    "\n",
    "# 定义Json解析器\n",
    "parser = JsonOutputParser()\n",
    "\n",
    "#以PromptTemplate为例\n",
    "prompt_template = PromptTemplate.from_template(\n",
    "    template=\"回答用户的查询\\n 满足的格式为{format_instructions}\\n 问题为{question}\\n\",\n",
    "    partial_variables={\"format_instructions\": parser.get_format_instructions()},\n",
    ")\n",
    "\n",
    "prompt = prompt_template.invoke(input={\"question\": joke_query})\n",
    "response = chat_model.invoke(prompt)\n",
    "print(response)\n",
    "\n",
    "json_result = parser.invoke(response)\n",
    "print(json_result)"
   ],
   "id": "467076fae26841b8",
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/opt/miniconda3/envs/pyth310/lib/python3.10/site-packages/requests/__init__.py:86: RequestsDependencyWarning: Unable to find acceptable character detection dependency (chardet or charset_normalizer).\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "content='```json\\n{\\n  \"joke\": \"为什么海洋总是很友好？因为它有很多波浪（waves）！\"\\n}\\n```' additional_kwargs={'refusal': None} response_metadata={'token_usage': {'completion_tokens': 33, 'prompt_tokens': 32, 'total_tokens': 65, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_efad92c60b', 'id': 'chatcmpl-CKwmNzYMeKbQuhqk77GvuPCO8uXi8', 'service_tier': None, 'finish_reason': 'stop', 'logprobs': None} id='run--065b274b-eb19-49d9-ba07-059f941f4f55-0' usage_metadata={'input_tokens': 32, 'output_tokens': 33, 'total_tokens': 65, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}}\n",
      "{'joke': '为什么海洋总是很友好？因为它有很多波浪（waves）！'}\n"
     ]
    }
   ],
   "execution_count": 1
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "使用|符号以后的举例：",
   "id": "5a27290128507b24"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-29T01:16:38.532731Z",
     "start_time": "2025-09-29T01:16:37.206974Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "# 引入依赖包\n",
    "from langchain_core.output_parsers import JsonOutputParser\n",
    "from langchain_core.prompts import PromptTemplate\n",
    "\n",
    "# 初始化语言模型\n",
    "chat_model = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "joke_query = \"告诉我一个笑话。\"\n",
    "\n",
    "# 定义Json解析器\n",
    "parser = JsonOutputParser()\n",
    "\n",
    "#以PromptTemplate为例\n",
    "prompt_template = PromptTemplate.from_template(\n",
    "    template=\"回答用户的查询\\n 满足的格式为{format_instructions}\\n 问题为{question}\\n\",\n",
    "    partial_variables={\"format_instructions\": parser.get_format_instructions()},\n",
    ")\n",
    "# 写法1：\n",
    "# prompt = prompt_template.invoke(input={\"question\":joke_query})\n",
    "# response = chat_model.invoke(prompt)\n",
    "# json_result = parser.invoke(response)\n",
    "\n",
    "# 正确的写法\n",
    "chain = prompt_template | chat_model | parser\n",
    "\n",
    "# 错误的写法\n",
    "# chain =  chat_model |  prompt_template | parser\n",
    "json_result = chain.invoke(input={\"question\": joke_query})\n",
    "print(json_result)"
   ],
   "id": "9ea8c80880472c7",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'joke': '为什么鸡过马路？为了到另一边！'}\n"
     ]
    }
   ],
   "execution_count": 2
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
